﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WarehouseManagement.BusinessLogic.BC;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.BusinessLogic.DTOConverter;
using WarehouseManagement.ViewModels.Export;
using WarehouseManagement.ViewModels.Merchandise;
using WarehouseManagement.Views.Export;

namespace WarehouseManagement.Presenters.Export
{
    public class NewEditExportPresenter : BasePresenter<INewEditExportViewModel>
    {
        private CustomerBC _custBC;
        private ExportBC _exportBC;
        private MerchandiseBC _merchandiseBC;
        private StockBC _stockBC;
        public delegate void ExportSaved(bool success);
        public ExportSaved OnExportSaved;
        private BindingList<ExportDetailDTO> _exportDetails;


        public NewEditExportPresenter()
        {
            _custBC = new CustomerBC();
            _exportBC = new ExportBC();
            _merchandiseBC = new MerchandiseBC();
            _stockBC = new StockBC();
            _exportDetails = new BindingList<ExportDetailDTO>();
        }

        protected override void WireupEventHandles()
        {

        }

        public void InitializeView()
        {
            if (Model.CurrentEditMode == NewEditExport.EditMode.New)
            {
                Model.ExportDate = DateTime.Now;
                //Model.ExportNumber = _exportBC.GenerateNewExportNumber();
                this.CreateNewExportNumber();
            }
            LoadCustomerList();
            LoadMerchandiseLookupData(DateTime.Now);
            Model.ExportDetails = _exportDetails;


        }

        public void LoadMerchandiseLookupData(DateTime from)
        {
            var list = _merchandiseBC.GetMerchandiseList();


            List<dynamic> l = new List<dynamic>();
            foreach (var item in list)
            {
                var merchandiseInStock = _stockBC.GetViewStockInfo(item.Id, from.Date,from.Date);
                var originPrice = 0m;
                if (merchandiseInStock.EndPeriodQuantity != 0)
                {
                    originPrice = merchandiseInStock.EndPeriodValue / (decimal)merchandiseInStock.EndPeriodQuantity;
                }

                double orderedQty = 0;
                double avaiQty = 0;
                orderedQty = 0;
                avaiQty = merchandiseInStock.EndPeriodQuantity - orderedQty;

                l.Add(
                    new
                    {
                        Id = item.Id,
                        MerchandiseUnit = item.Unit,
                        MerchandiseId = item.Id,
                        item.MerchandiseName,
                        QuantityInStock = merchandiseInStock.EndPeriodQuantity,
                        OriginPrice = originPrice,
                        ValueInStock = merchandiseInStock.EndPeriodValue,
                        OrderedQuantity = orderedQty,
                        AvailableQuantity = avaiQty
                    });
            }

            Model.MerchandiseList = l;
        }

        public void LoadCustomerList()
        {
            Model.CustomerList = _custBC.GetCustomerList()
                .Select(e => CustomerConverter.Convert(e))
                .ToList();
        }

        public void SelectMerchandise()
        {
            //SaleManagement.Views.Shared.SelectMerchandise frm = new Views.Shared.SelectMerchandise();
            //frm.ShowOrderedQuantity = true;
            //frm.OnMerchandiseSelected += new ViewModels.Merchandise.MerchandiseSelected(OnMerchandiseSelected);
            //frm.ShowDialog();
        }

        public void LoadExportList()
        {
            var list = _exportBC.GetExportDetailList(Model.ExportNumber);
            foreach (var item in list)
            {
                Model.ExportDetails.Add(item);
            }
        }
        public void LoadExportInfo()
        {
            var exp = _exportBC.GetExportByNumber(Model.ExportNumber);
            if (exp != null)
            {
                Model.ExportReason = exp.ExportReason;
                Model.CustomerId = exp.CustomerId;
                Model.Notes = exp.Notes;
            }
        }

        public void Export()
        {
            //if (Model.SelectedMerchandise == null)
            //{
            //    MessageBox.Show("Bạn chưa chọn mặt hàng");
            //    return;
            //}
            //var dto = new ExportDTO()
            //{
            //    CustomerId = Model.ExportToCustomer == null ? null : (int?)Model.ExportToCustomer.Id,
            //    ExportDate = DateTime.Now,
            //    ExportPrice = Model.ExportPrice,
            //    IsCancelled = false,
            //    Merchandise = Model.SelectedMerchandise,
            //    Notes = Model.Notes,
            //    Quantity = Model.ExportQuantity

            //};
            //_ieBC.Export(dto);
            //LoadExportList();
            //ResetModel();
        }

        private void ResetModel()
        {
            //Model.Notes = string.Empty;
            //Model.SelectedMerchandise = null;
            //Model.ExportPrice = 0;
            //Model.ExportQuantity = 1;

        }

        private void OnMerchandiseSelected(WarehouseManagement.BusinessLogic.DTO.MerchandiseDTO item)
        {
            //Model.SelectedMerchandise = item as ExtraMerchandiseDTO;
            ////Model.AverageImportUnitPrice = _ieBC.GetAverageImportUnitPrice(DateTime.Now.Date, item.Id);
            //if (MerchandiseSelected != null)
            //    MerchandiseSelected(item);
        }




        public void DeleteSelectedItem()
        {
            RemoveExportDetailItem(Model.SelectedExportItem);
        }

        private void RemoveExportDetailItem(Guid detailId)
        {
            var selectedItemId = detailId;

            if (selectedItemId != Guid.Empty)
            {
                var item = _exportDetails.SingleOrDefault(e => e.Id == selectedItemId);
                _exportDetails.Remove(item);
            }
        }

        public void CreateNewExportNumber()
        {
            _exportBC.RecycleContext();


            Model.ExportId = Guid.NewGuid();

            Model.ExportNumber = _exportBC.GenerateNewExportNumber();
            Model.ExportDate = DateTime.Now;
            _exportDetails = new BindingList<ExportDetailDTO>();
            _exportDetails.Clear();
            Model.ExportDetails = _exportDetails;
            Model.Notes = Model.ExportReason = string.Empty;
            Model.CurrentEditMode = NewEditExport.EditMode.New;
        }

        private void ReassignAvailableQuantity()
        {
            foreach (var item in this._exportDetails)
            {
                if (item.IsSaved)
                {
                    var obj = _stockBC.GetMerchandiseInStockCurrentTime(item.MerchandiseId, DateTime.Now);
                    var orderedQty = 0;
                    item.AvailableExportQuantity = obj.QuantityInStock - orderedQty;
                }
            }
        }

        public void SaveExport()
        {
            var import = new ExportDTO()
            {
                Id = Model.ExportId,
                ExportDate = Model.ExportDate,
                ExportNumber = Model.ExportNumber,
                ExportReason = Model.ExportReason,
                Notes = Model.Notes,
                CreatedDate = DateTime.Now,
                CustomerId = Model.CustomerId
            };


            try
            {

                _exportBC.SaveExport(import,
                    _exportDetails.ToList(),
                    Model.CurrentEditMode == NewEditExport.EditMode.EditExisting);
                LoadMerchandiseLookupData(DateTime.Now);
                ReassignAvailableQuantity();
                if (OnExportSaved != null)
                    OnExportSaved(true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Đã xảy ra lỗi khi xuất kho. Các thao tác đã bị hủy, bạn hãy thử lại sau" + ex.Message, "Lỗi khi xuất kho", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (OnExportSaved != null)
                    OnExportSaved(false);
            }
        }
    }
}
